#!/usr/bin/env bash

source "$CONFIG_DIR/environment"
source "$THEME_DIR/tokyonight"

create_workspace_bracket_for_monitor() {
  parameters=("$@")
  monitor_id=${parameters[0]}
  monitor_workspaces=("${parameters[@]:1}")

  # 给第一个显示器左边加点空白
  sketchybar --add item workspaces_spacer_left left \
    --set workspaces_spacer_left \
    width=7 \
    background.drawing=off \
    label.drawing=off

  # 画出所有 workspace 名称
  for workspace_id in ${monitor_workspaces[@]}; do
    sketchybar --add item workspaces."$monitor_id"."$workspace_id" left \
      --subscribe workspaces."$monitor_id"."$workspace_id" aerospace_workspace_change \
      --set workspaces."$monitor_id"."$workspace_id" \
      background.drawing=off \
      click_script="aerospace workspace $workspace_id" \
      label="$workspace_id" \
      label.width="18" \
      script="$PLUGIN_DIR/aerospace $workspace_id"
  done

  if [ $monitor_id -lt ${#monitor_ids[@]} ]; then # 不是最后一个显示器，在右侧加分割线
    sketchybar --add item workspaces_monitor_separator."$monitor_id" left \
      --set workspaces_monitor_separator."$monitor_id" \
      background.drawing=off \
      label.padding_left=-5 \
      label.font.size="$BACKGROUND_HEIGHT" \
      label.width="15" \
      label="|"
  else # 最后一个显示器，不画分割线，加一个默认隐藏的 service mode 标识，激活 service mode 时才显示
    sketchybar --add item workspaces_service_mode left \
      --subscribe workspaces_service_mode aerospace_service_mode_enabled_changed \
      --set workspaces_service_mode \
      background.drawing=off \
      label.drawing=off \
      label.highlight=on \
      label.font="$LABEL_HIGHLIGHT_FONT" \
      label="[s]" \
      label.padding_right=8 \
      script="$PLUGIN_DIR/aerospace $AEROSPACE_SERVICE_MODE_ENABLED"

    sketchybar --add item workspaces_spacer_right left \
      --set workspaces_spacer_right \
      width=2 \
      background.drawing=off \
      label.drawing=off
  fi

  sketchybar --add bracket workspaces."$monitor_id" /workspaces\.*/ \
    --set workspaces."$monitor_id" \
    background.padding_left="30" \
    background.corner_radius="$BRACKET_BACKGROUND_CORNER_RADIUS" \
    background.border_width="$BRACKET_BACKGROUND_BORDER_WIDTH"
}

sketchybar --add event aerospace_workspace_change
sketchybar --add event aerospace_service_mode_enabled_changed

monitor_ids=($(aerospace list-monitors | awk '{print $1}'))

# TODO:
# - Update this view when moving workspaces to a different monitors.
# - Only show workspaces with active windows or currently selected like in i3
#   default configuration.
for monitor_id in ${monitor_ids[@]}; do
  workspaces_for_monitor_id=($(aerospace list-workspaces --monitor $monitor_id))
  create_workspace_bracket_for_monitor $monitor_id "${workspaces_for_monitor_id[@]}"
done
